function UserGroup(){
    this.tab=this.InitTab();
	this.form=this.InitEleUI();

	this.grid=this.InitGrid();
	
	this.orgidobj=null;
}


UserGroup.prototype.InitEleUI=function(){
	var form;
	layui.use('form', function(){
       form = layui.form; //只有执行了这一步，部分表单元素才会自动修饰成功
	   form.render();
	});  
	return form;
}
UserGroup.prototype.InitTab=function(){
	var element;
	var _this=this;
	layui.use('element', function(){
	   element = layui.element;
	   element.on('tab(tabcontent)', function(data){
		   //alert(data.index);
		    if(data.index==0){
		    	_this.comboboxm.setEnabled();
		    	document.formedit.reset();
		    	document.formedit.orgid.value=0;
		    	_this.form.render();
		    }
		    
	   })
	});
	return element;
}

UserGroup.prototype.OpTab=function(tabindex,obj){
	this.tab.tabChange('tabcontent', tabindex);
	//this.orgidobj=obj;
	if(obj){
		document.formedit.orgname.value=obj.orgname;
		 document.formedit.remark.value=obj.remark;
		 document.formedit.orgid.value=obj.orgid;
		 document.formedit.orderindex.value=obj.orderindex;
		 this.comboboxm.selectValue(obj.orgparentid);
		 this.comboboxm.setDisabled();
		 this.form.render();
		 //this.form.render('select');
	}
}


UserGroup.prototype.openadduser=function(groupid,orgparentid){
	top.mylayui.open({
         type: 2,
         title: '用户添加',
         shadeClose: true,
         shade: 0.5,
         area: ['870px', '550px'],
         content: 'org/group_user?groupid='+groupid+"&orgparentid="+orgparentid
       }); 

	var iframeele=top.$(".layui-layer-content").find('iframe');
	iframeele.css({"height":$(iframeele).height()-10});
}

UserGroup.prototype.deleteentity=function(orgid){
	top.mylayui.confirm('确定要删除吗？',{icon: 0}, function(index){
   	 top.mylayui.close(index);
   	 
	$.ajax({
		type:"POST",
		url:"delete_org",
		data:{orgid:orgid},
		beforeSend:function(XHR){
			
		},
		success:function(data){
			data=eval('('+data+')');
			if(data.result>0){
				top.mylayui.msg(data.msg, {icon: 1});
				//vOrg.searchtable();
				document.location.reload();
			}
			else{
				top.mylayui.msg(data.msg, {icon: 0});
			}
		},
		complete:function(XHR){
			
		},
		error:function(){
			
		}
	});
	})
}

UserGroup.prototype.funeditentity=function(orgid,orgname,orgparentid,remark,orderindex){
	var data={orgid:orgid,orgname:orgname,orgparentid:orgparentid,remark:remark,orderindex:orderindex};
	vGroup.OpTab(2,data);
}

UserGroup.prototype.InitGrid=function (){
	var _this = this;
    window.liger.remove("list");
    if (_this.grid == null) {
        _this.grid = $("#list").ligerGrid({
            columns: [
                      //{ display: '序号', width: 80, name: 'rowNum' },
                     { display: '机构名称', width:250, align:'left',name: 'orgname',id:"orgname", render: function (rowdata, rowindex, value) {
                    	 if(rowdata.orgtype==1){
                    		 return value+'('+rowdata.usercount+')';
                    	 }else{
                    		 return value;
                    	 }
                     }},
                     { display: '创建时间', width: 180, name: 'createtime', render: function (rowdata, rowindex, value) {
                     	return value;
                      } },
                     { display: '描述', width: 200, name: 'remark' },
                     {display: '操作', width: 100, name: 'userid', render: function (rowdata, rowindex, value) {
                    	if(rowdata.orgtype==1){
                    		 var html=' <img class="btn-img" style="vertical-align:middle" src="'+ctxStatic+'/images/button/jieshou.png" onclick="vUserGroup.openadd('+rowdata.orgid+','+rowdata.orgparentid+')"  alt="设置人员" title="设置人员">';
                         	if(rowdata.usercount>0){
                         		 html+='<img class="btn-img" style="vertical-align:middle" src="'+ctxStatic+'/images/button/detail.png" onclick="vUserGroup.SkipDetail('+rowdata.orgid+')"  alt="详情" title="详情">';
                         	}
                    		
                         	//html+=' <img class="btn-img" style="vertical-align:middle" src="'+ctxStatic+'/images/button/setuser.png" onclick="vGroup.openadduser('+rowdata.orgid+','+rowdata.orgparentid+')" alt="设置人员" title="设置人员">';
                         	return html;
                    	}
                    	
                     }}
            ],
            pageSize: 30,
            url: "get_list_group" + '?time=' + new Date().getTime(),
            delayLoad: false,            //初始化时是否加载,为true时,不加载,为false时,则加载
            sortName: null,
            dataAction: 'server',
            parms: {
                Method: "",
                rolename: $("#rolename").val()
            },
            sortOrder: null,
            sourceObj: _this.grid,
            root: 'items',                       //数据源字段名
            record: 'countRecord',                    //数据源记录数字段名
            pageParmName: 'CurrentPage',               //页索引参数名，(提交给服务器)
            pagesizeParmName: 'PageSize',        //页记录数参数名，(提交给服务器)
            data: {},
            width: "100%",
            height: '100%',
            heightDiff: 0,
            rowHeight:28,
            onSuccess: function (rowdata, rowindex) { if (rowdata.status > 0) { alert(rowdata.msg) } },
            alternatingRow: true,
            border: 0,
            usePager:false,
            tree:{
            	columnId:"orgname",
            	idField:"orgid",
            	parentIDField:"orgparentid"
            	
            }
        })
    }
}

UserGroup.prototype.openadd=function(orgid,parenid){
	top.mylayui.open({
        type: 2,
        title: '设置人员',
        shadeClose: true,
        shade: 0.5,
        area: ['950px', '550px'],
        content: 'usergroup/user_group_set?groupid='+orgid+'&szdw='+parenid
      }); 
}

UserGroup.prototype.SkipDetail=function(groupid){
	 this.OpTab(2);
	 this.InitTableByBt(groupid);
}

UserGroup.prototype.InitTableByBt=function (groupid){
	var table;
	var _this=this;
	layui.use('table', function() {
	    table = layui.table;
	    table.init('detaillist', {
			height : $(window).height() - 120
			,url : 'get_list_user_detail' // 数据接口
			,page : true // 开启分页
			,limit : 40
			,id: 'detaillist'
			,limits:[20,40,80,100]
	        ,page:false
			,method:"post"
				,request:{
					type:'post'
				}
				,where:{
					groupid:groupid
			    
					}
			    ,done: function(res, page, count){
			    	var dataarr=res.data;
			    }
				
				
		  });
	    
	    
	    //监听工具条
	    table.on('tool(detaillist)', function(obj){
	      var data = obj.data;
	      if(obj.event === 'del'){
	    	  vUserGroup.deleteset(obj.data.userid);
	      } 
	    });
	    
	    
	})
	
	return table;
	
	

}

UserGroup.prototype.addresult=function(userids,groupid){
	$.ajax({
		type:"POST",
		url:"add_user_group",
		data:{userids:userids,groupid:groupid},
		beforeSend:function(XHR){
			
		},
		success:function(data){
			data=eval('('+data+')');
			if(data.result>0){
				top.mylayui.msg(data.msg, {icon: 1});
				top.mylayui.closeAll('iframe');
				document.location.reload();
			}
			else{
				top.mylayui.msg(data.msg, {icon: 0});
			}
		},
		complete:function(XHR){
			
		},
		error:function(){
			
		}
	});
}


UserGroup.prototype.deleteset=function(userid){
	$.ajax({
		type:"POST",
		url:"update_user_group",
		data:{userid:userid},
		beforeSend:function(XHR){
			
		},
		success:function(data){
			data=eval('('+data+')');
			if(data.result>0){
				top.mylayui.msg(data.msg, {icon: 1});
				top.mylayui.closeAll('iframe');
				document.location.reload();
			}
			else{
				top.mylayui.msg(data.msg, {icon: 0});
			}
		},
		complete:function(XHR){
			
		},
		error:function(){
			
		}
	});
}


var vUserGroup;
$(function () {
	vUserGroup = new UserGroup();
})


function CloseDialog(result,msg){
	if(result>0){
		top.mylayui.msg('操作成功', {icon: 1});
		document.formedit.reset();
		//vOrg.searchtable();
		//vOrg.OpTab(1);
		document.location.reload();
	}
	else{
		if(msg){
			top.mylayui.msg(msg, {icon: 0});
		}else{
			top.mylayui.msg('操作失败', {icon: 0});
		}
	}
}


/*
 * 传入的数组有id和父节点pid字段，通过它们的关联构造成一棵或多棵树结构
 * @param nodes 集合
 * @param treeRootId 根节点的id
 */
function createTreeData(nodes, treeRootId) {
    var groups = {};
    var treeRootPid=0;
    // 按父节点将节点分组
    for (var i in nodes) {
        if (!groups[nodes[i].orgparentid]) {
            groups[nodes[i].orgparentid] = [];
        }
        groups[nodes[i].orgparentid].push(nodes[i]);
        if (treeRootPid && treeRootPid === nodes[i].orgid) { // 发现传入的根节点id作为节点id时，将根节点设置为该节点的父节点
            treeRootPid = nodes[i].orgparentid;
        }
    }

    var rootNodes = groups[treeRootPid];
    //rootNodes.name=rootNodes.orgname;
    //rootNodes.id=rootNodes.orgid;
    groups[treeRootPid] = null; // [SAFEGUARD]防止自为父节点或互为父节点（有环图结构）导致的死循环
    function traverseTreeNodeGroup(treeNodeGroup) {
        for (var i in treeNodeGroup) {
            var node = treeNodeGroup[i];
            node.name=node.orgname;
            node.id=node.orgid;
            node.spread=true;
            if (groups[node.orgid]) {
                node.children = groups[node.orgid];
                groups[node.orgid] = null; // [SAFEGUARD]防止自为父节点或互为父节点（有环图结构）导致的死循环
                traverseTreeNodeGroup(node.children);
            }
        }
    }
    traverseTreeNodeGroup(rootNodes);
    return rootNodes;
}